package com.erebus.config;

import com.alibaba.fastjson.JSON;
import com.erebus.model.dto.AuthParamsDto;
import com.erebus.model.dto.UserExt;
import com.erebus.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


//重写了AuthProviderCustom的校验的密码的方法，统一认证入口，有一些认证方式不需要校验密码
@Component
public class AuthProviderCustom implements AuthenticationProvider {


    @Autowired
    ApplicationContext applicationContext;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        //将传入的json转成AuthParamsDto对象
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(username, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }

        //认证类型，有password，wx。。。
        String authType = authParamsDto.getAuthType();

        //根据认证类型从spring容器取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        //调用统一execute方法完成认证
        UserExt userExt = authService.execute(authParamsDto);

        // 假如验证成功，怎么返回token给前端，而不是重定向地址



        return new UsernamePasswordAuthenticationToken( // 写入token
                userExt, // 用户信息
                null, // 密码
                null // 权限
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}